<template>
  <div class="card">
    <div class="list_stocks"><span> 股池列表</span></div>
    <div v-if="stocks.length">
      <div class="card_wrapper">
        <div v-for="(item, index) in stocks" :key="index">
          <div @click="clickStrStat(item.gpcId)">
            <div class="card_top_title">
              <div class="title_left" @click="toDetail(item.gpcId, item.name)">
                <div>
                  <img :src="require('../assets/images/' + item.imgName + '.png')" alt="" />
                </div>
                <div>
                  <div class="name">{{ item.name }}</div>
                  <div>{{ item.label }}</div>
                </div>
              </div>
              <div
                class="subscribe_btn"
                :style="item.btnGray ? bgcolor : 'background-color: #319EFF'"
                @click="stocksSub(item.gpcId, item.pushtype, index, item.btnGray)"
              >
                <span v-if="!item.btnGray">+订阅</span>
                <span v-else>取消订阅</span>
              </div>
            </div>
            <div class="card_content" @click="toDetail(item.gpcId, item.name)">
              <div>简介：{{ item.des }}</div>
              <div>投入：{{ item.input }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-else>
      <NoData />
    </div>
    <!-- 个股列表 -->
    <div class="stock_list_wrapper" v-if="showStockList">
      <div class="stock_list_content">
        <div class="list_tips">跟踪中个股</div>
        <div v-if="stockList.length">
          <div class="active_cp_wrapper" v-for="(item, index) in stockList" :key="index">
            <div class="is_selected_content_wrapper">
              <!-- 股票代码、名称、涨跌幅 -->
              <div class="is_selected_content" @click="linkToKline(item.stockCode, item.market)">
                <div>
                  <span v-if="item.stockName">{{ item.stockName }}</span>
                  <span v-else>--</span>
                  <span>{{ item.stockCode }}</span>
                </div>

                <div>
                  <span v-if="item.upDownPercent > 0" class="up_data">
                    {{ item.nowPrice }}
                  </span>
                  <span
                    v-else-if="item.nowPrice.length && Number(item.nowPrice) === 0"
                    class="zero_data"
                  >
                    {{ item.nowPrice }}
                  </span>
                  <span v-else-if="item.nowPrice === '' || item.nowPrice === -9999"> -- </span>
                  <span v-else class="down_data">
                    {{ item.nowPrice }}
                  </span>
                </div>
                <div>
                  <span v-if="item.upDownPercent > 0" class="up_data">
                    {{ item.upDownPercent }}%
                  </span>
                  <span
                    v-else-if="item.upDownPercent && Number(item.upDownPercent) === 0"
                    class="zero_data"
                  >
                    {{ item.upDownPercent }}%
                  </span>
                  <span v-else-if="item.upDownPercent === '' || item.nowPrice === -9999"> -- </span>
                  <span v-else-if="item.upDownPercent < 0" class="down_data">
                    {{ item.upDownPercent }}%
                  </span>
                  <span v-else>--</span>
                </div>
              </div>
              <div
                class="subscribe_btn"
                :style="item.btnGray ? bgcolor : 'background-color: #319EFF'"
                @click="
                  stockListSub(
                    item.stockId,
                    item.stockCode,
                    item.gpc,
                    index,
                    item.btnGray,
                    item.pushtype
                  )
                "
              >
                <span v-if="!item.btnGray">+跟踪</span>
                <span v-else>取消跟踪</span>
              </div>
            </div>
            <div class="cp_detail_content" @click="linkToKline(item.stockCode, item.market)">
              <div>
                <div>买入价格</div>
                <div v-if="item.buyPrice" v-hxm-redgreen>{{ item.buyPrice }}</div>
                <div v-else-if="Number(item.buyPrice) === 0">
                  {{ item.buyPrice }}
                </div>
                <div v-else>--</div>
              </div>
              <div>
                <div>最高涨幅</div>
                <div v-if="item.highestProfit" v-hxm-redgreen>{{ item.highestProfit }}%</div>
                <div v-else-if="Number(item.highestProfit) === 0">
                  {{ parseFloat(item.highestProfit).toFixed(2) }}%
                </div>
                <div v-else>--</div>
              </div>
              <div>
                <div>区间涨幅</div>
                <div v-if="item.rangeProfit" v-hxm-redgreen>{{ item.rangeProfit }}%</div>
                <div v-else-if="Number(item.rangeProfit) === 0">
                  {{ parseFloat(item.rangeProfit).toFixed(2) }}%
                </div>
                <div v-else>--</div>
              </div>
              <div>
                <div>入选时间</div>
                <div v-if="item.buyDate">{{ item.buyDate }}</div>
                <div v-else>--</div>
              </div>
            </div>
          </div>
        </div>
        <div v-else><NoData /></div>
      </div>
    </div>
    <div>
      <SubscribeTemplate
        :isShow="isShowTemplate"
        :gpcId="isSelectId"
        :infoIndex="infoIndex"
        @changeStatus="SubscribeTemplate"
      >
      </SubscribeTemplate>
    </div>
  </div>
</template>

<script>
import config from '@/config/index.js';
import SubscribeTemplate from './common/SubscribeTemplate';
import {
  jumpTokline,
  redgreenhandler,
  stopBodyScroll,
  webHQCommon,
  apiDataDeal,
} from '../utils/index';
import NoData from './common/NoData.vue';
import { GET_SUB, SET_SUB, GET_QUERY_INDEX_SUBSCRIBE, cfxfJudgeAuth } from '@/apis';
export default {
  name: 'StockList',
  data() {
    return {
      stocks: [], //股池
      stockList: [], //个股
      globalPushType: '',
      bgcolor:
        window.getCssStyle() === 'black' ? 'background-color:#222222' : 'background-color:#cccccc',
      showStockList: window.getParam('product') === 'jtzz',
      isShowTemplate: false, //二期订阅方式组件
      isSelectId: '',
      infoIndex: '',
    };
  },
  components: {
    NoData,
    SubscribeTemplate,
  },
  computed: {
    //重新加载
    infoDataStatus() {
      return this.$store.state.baseInfo.infoData;
    },
  },
  watch: {
    infoDataStatus: {
      handler(newValue) {
        if (typeof newValue === 'string') {
          this.$set(this.stocks[Number(newValue)], 'btnGray', true);
          this.getAllStocks();
        }
      },
    },
  },
  async mounted() {
    const product = window.getParam('product');
    // 获取股池订阅类型
    this.stocks = config.stocksList[product];
    if (product === 'cfxf') {
      const result = await this.cfxfJudgeAuthFn();
      if (!result) {
        const ybyxGpcId=118;
        this.stocks = this.stocks.filter(item => item.gpcId !== ybyxGpcId);
      }
    }
    this.getAllStocks();
    registerWebListener('onShow', () => {
      this.getAllStocks();
    });
  },
  methods: {
    async cfxfJudgeAuthFn() {
      try {
        const result = await cfxfJudgeAuth();
        if (!result) {
          return false;
        }
        const resultArr = result.result || [];
        const validId=6;
        return resultArr.includes(validId);
      } catch (error) {
        _t.errorReport({name:`StockList.vue组件中方法cfxfJudgeAuthFn错误。${error.name}`,message:`接口url：${_Global.api.getuserlimit}。${error.message}`,stack:error.stack,category:'js'});
      }
    },
    dialogCommon(title, content) {
      stopBodyScroll();
      this.$dialog({
        title,
        content,
        btns: [
          {
            text: '我知道了',
            callback: () => {
              stopBodyScroll();
            },
          },
        ],
      });
    },
    //二期股池订阅
    SubscribeTemplate(arr) {
      this.isShowTemplate = arr.showStatus;
      // 根据子组件传来的状态 设置按钮状态
      this.$set(this.stocks[arr.setIndex], 'btnGray', arr.setGray);
    },
    // 获取股池列表状态
    async getAllStocks() {
      // 非价投至尊 只用来判断有没有订阅,具体查询点击的时候开始查
      const params = {};
      if (!this.showStockList) {
        params.type = 1; //查询全部股票池中订阅了哪些股票池
        params.version = getParam('product') === 'jtzz' ? 2 : 1; //1-金融大师，2-价投组合
        params.data = true;
        const res = await GET_SUB(params);
        this.dealSub(res);
        const query = {};
        //获取强龙低吸、多头趋势、热点轮动、深一度、小盘成长、价值成长订阅状态
        query.pool_ids = '2072,3,11,6,2,734';
        try {
          const subData = await GET_QUERY_INDEX_SUBSCRIBE(query);
          this.dealSubIndex(subData);
          this.$pageStatus.close();
          return;
        } catch (error) {
          _t.errorReport({name:`StockList.vue组件中方法getAllStocks错误。${error.name}`,message:`接口url：${_Global.api.indexSubStatus}，参数：${JSON.stringify(params)}。${error.message}`,stack:error.stack,category:'js'});
        }
      }
      const result=await this.dealGetAllStocks();
      if(!result){
        this.$pageStatus.fail(() => {
          this.$toast('刷新成功');
          //获取股池订阅状态
          this.getAllStocks();
          // 加载订阅信息
          this.$store.commit('setBaseInfo', { reload: 'loading' });
        });
      }
    },
    dealSub(res){
      const ggzcIdOld=4;
      const ggzcIdNew=2;
      res.data.forEach(element => {
          if (!element.stock_id) {
            //已订阅的股池
            this.stocks.forEach((ele, index) => {
              if (
                [
                  Number(ele.name === 'AI高管增持' && ele.gpcId === ggzcIdOld ? ggzcIdNew : ele.gpcId),
                  ele.gpcId,
                ].includes(Number(element.gpc_id))
              ) {
                // 数据展示兜底字段
                this.$set(this.stocks[index], 'btnGray', true);
              }
            });
          }
        });
    },
    dealSubIndex(subData){
      if (Number(subData.errorcode) === 0) {
          for (const item in subData.result) {
            if (subData.result[item].length && item) {
              //已订阅的股池
              this.dealSubIndexSuccess(item);
            }
          }
        }
    },
    dealSubIndexSuccess(item){
      const ggzcIdOld=4;
      const ggzcIdNew=2;
      this.stocks.forEach((ele, index) => {
                if (['AI高管增持', 'AI强龙低吸', '热点轮动'].includes(ele.name)) {
                  return;
                }
                if (Number(item) === Number(ele.gpcId === ggzcIdOld ? ggzcIdNew : ele.gpcId)) {
                  // 数据展示兜底字段
                  this.$set(this.stocks[index], 'btnGray', true);
                }
      });
    },
    async dealGetAllStocks(){
      const versionJtzzNum=2;
      const versionNotJtzzNum=1;
      const typeNum=3;
      const safeTime=500;
      const params = {
        type:typeNum,
        version:window.getParam('product') === 'jtzz' ? versionJtzzNum : versionNotJtzzNum,
        data:true,
      };
      const res = await GET_SUB(params);
      if (Number(res.code) === 0 && res.data) {
        if (res.data.length) {
          this.getStockStatus();
          res.data.forEach(item => {
            this.globalPushType = item.push_type.join(',');
            return true;
          });
        }
        setTimeout(() => {
          this.$pageStatus.close();
        }, safeTime);
        return true;
      }
      return false;
    },
    // 获取股池和个股列表状态
    async getStockStatus() {
      const params = {
        type: 3,
        version: getParam('product') === 'jtzz' ? 2 : 1,
        data: true,
      };
      const res = await GET_SUB(params);
      if (Number(res.code) === 0) {
        if (res.data) {
          if (!window.getAppVersion()) return;
          const results = res.data;
          this.stockList = [];
          const stockIdArr = [];
          const marketIdArr = [];
          results.forEach((element, key) => {
            if (!element.stock_id) {
              //已订阅的股池
              this.stocks.forEach((ele, index) => {
                if (Number(element.gpc_id) === Number(ele.gpcId)) {
                  // 数据展示兜底字段
                  this.$set(this.stocks[index], 'btnGray', true);
                }
                ele.pushtype = this.globalPushType;
              });

              this.$pageStatus.close();
              return;
            }
            stockIdArr.push(element.stock_code);
            marketIdArr.push(element.market.toString());
            element.range_profit = redgreenhandler(element.range_profit) / 100;
            element.highest_profit = redgreenhandler(element.highest_profit) / 100;
            //跟踪的个股
            this.stockList.push(
              apiDataDeal(element, this.globalPushType, null, null, this.showStockList)
            );
          });
          webHQCommon(stockIdArr, marketIdArr, this.stockList, list => {
            this.stockList = list;
          });
        }
        return;
      }
      this.$toast('股池列表获取异常');
    },
    /**
     * 订阅退订功能
     * 状态码说明：
     * 订阅成功：0 订阅失败：-1  参数不规范：-2 订阅股票池数量已达到上限：-3  订阅股票数量已达到上限：-4 订阅股票必须先订阅股票池：-5  未找到订阅数据：-6
     * */
    async stocksSub(gpc, pushtype, index, status) {
      // 非价投至尊
      if (!this.showStockList) {
        this.isShowTemplate = !this.isShowTemplate;
        // 在子组件里监听此项进行接口调用
        this.isSelectId = gpc;
        this.infoIndex = index;
        return;
      }
      if (!status) {
        // 1.设置订阅之前,需要满足股池订阅数量不能超过3个
        //订阅逻辑
        if (pushtype) {
          //判断有无订阅方式
          let params = {
            version: getParam('product') === 'jtzz' ? 2 : 1, //订阅限制，1-没有限制，2-按照股票池的规则，所有股票池只能订阅两个
            gpc,
            pushtype,
          };
          const res = await SET_SUB(params);
          if (Number(res.code) === 0 && res.data) {
            //2.订阅接口请求成功之后，改变对应按钮的状态值
            this.$set(this.stocks[index], 'btnGray', true);
            this.$toast(res.data);
            this.$store.commit('setBaseInfo', { reload: 'loading' });
          } else if (Number(res.code) === -1 && res.data) {
            this.$toast(res.data); //订阅失败
          } else if (Number(res.code) === -2 && res.data) {
            this.$toast(res.data); //参数错误
          } else if (Number(res.code) === -3 && res.data) {
            const title = res.data ? res.data : '订阅股票池数量已达到上限';
            const content = '跟踪个股需要订阅所在股池，您已订阅3个股池，请先取消订阅其他股池';
            this.dialogCommon(title, content);
          } else if (Number(res.code) === -4 && res.data) {
            const title = res.data ? res.data : '订阅个股数量已达到上限';
            const content = '跟踪个股需要订阅所在股池，您已跟踪5个个股，请先取消跟踪其他个股';
            this.dialogCommon(title, content);
          }
        } else {
          this.$toast('请先选择一种订阅方式');
          // 唤起订阅方式
          this.$store.commit('setBaseInfo', { isShowSubWay: true });
          this.$store.commit('setBaseInfo', { infoData: index });
          // 通过store将要订阅的股池id传到订阅方式组件中
          this.$store.commit('setBaseInfo', { gpcId: gpc });
        }
      } else {
        // 退订逻辑
        let params = {
          version: getParam('product') === 'jtzz' ? 2 : 1, //客户端类型，1-金融大师，2-价投组合
          gpc,
        };
        //取消订阅逻辑
        const res = await SET_SUB(params);
        if (Number(res.code) === 0 && res.data) {
          const query = {
            version: getParam('product') === 'jtzz' ? 2 : 1,
            gpc,
            type: 2, //订阅类型，1-股票池，2-股票，3-全部
          };
          this.$set(this.stocks[index], 'btnGray', false);
          this.$store.commit('setBaseInfo', { reload: 'loading' });
          //查询一下当前股池订阅下订阅的个股
          const result = await GET_SUB(query);
          if (Number(result.code) === 0 && result.data.length) {
            this.$toast('取消股池订阅成功，该股池下订阅的个股仍保持提醒。');
            return;
          }
          this.$toast('已为您取消该股池订阅');
        } else {
          this.$toast('取消订阅失败');
        }
      }
    },
    //个股订阅和取消
    async stockListSub(id, stockcode, gpcId, index, status, pushtype) {
      if (!status) {
        // 1.判断有无订阅方式
        if (pushtype) {
          //2.判断对应的股池是否订阅
          let params = {
            version: getParam('product') === 'jtzz' ? 2 : 1, //订阅限制，1-没有限制，2-按照股票池的规则，所有股票池只能订阅两个
            stockid: id,
            gpc: gpcId,
            stockcode,
            pushtype,
          };
          const res = await SET_SUB(params);
          if (Number(res.code) === 0 && res.data) {
            this.$set(this.stockList[index], 'btnGray', true);
            this.$toast(res.data);
            this.$store.commit('setBaseInfo', { reload: 'loading' });
          } else if (!res.data.length) {
            this.$toast('暂无订阅消息');
          } else {
            this.$toast('订阅失败');
          }
        } else {
          this.$toast('请先选择一种订阅方式或订阅对应的股池');
        }
      } else {
        //取消订阅
        let params = {
          version: getParam('product') === 'jtzz' ? 2 : 1, //订阅限制，1-没有限制，2-按照股票池的规则，所有股票池只能订阅两个
          stockid: id,
          gpc: gpcId,
          stockcode,
        };
        const res = await SET_SUB(params);
        if (Number(res.code) === 0 && res.data) {
          this.$toast('已为您取消跟踪');
          this.stockList.splice(index, 1);
          this.$store.commit('setBaseInfo', { reload: 'loading' });
        } else {
          this.$toast('取消订阅失败');
        }
      }
    },
    //去详情页
    toDetail(id, name) {
      // 二级页面使用2804跳转
      location.href = `${config.toNewPage}detail?gpc_id=${id}&name=${name}&product=${getParam(
        'product'
      )}`;
    },
    // 到K线详情页
    linkToKline(stockId, marketId) {
      jumpTokline(stockId, marketId);
    },
    //点击策略类型埋点
    clickStrStat(id) {
      const tempStr = `${config.stat.pageId}.${config.statMap[id]}`;
      window.hxmClickStat(tempStr, { url_ver: config.stat.url_ver });
    },
  },
};
</script>

<style lang="less" scoped>
.card {
  margin-top: 0.2rem;
  margin-bottom: 0.2rem;
}
.list_stocks {
  width: 7.42rem;
  font-size: 0.32rem;
  font-weight: bold;
  height: 0.8rem;
  line-height: 0.8rem;
  background-color: #ffffff;
  margin: 0 auto;
  span {
    padding: 0 0.24rem;
  }
}
[theme-mode='black'] .list_stocks {
  font-size: 0.32rem;
  font-weight: bold;
  height: 0.8rem;
  line-height: 0.8rem;
  background-color: #1a1a1a;
  color: #d9d9d9;
  width: 7.42rem;
  margin: 0 auto;
  span {
    padding: 0 0.24rem;
  }
}

.list_tips {
  font-size: 0.32rem;
  font-weight: bold;
  height: 0.8rem;
  line-height: 0.8rem;
  background-color: #ffffff;
  padding-left: 3.2%;
  width: 7.2rem;
  margin: 0 auto;
}
[theme-mode='black'] .list_tips {
  font-size: 0.32rem;
  font-weight: bold;
  height: 0.8rem;
  line-height: 0.8rem;
  background-color: #1a1a1a;
  color: #d9d9d9;
  padding-left: 3.2%;
  width: 7.2rem;
  margin: 0 auto;
}
.card_wrapper {
  position: relative;
  width: 7.42rem;
  background-color: #ffffff;
  font-size: 0.28rem;
  margin: 0 auto;
  .card_top_title {
    padding: 2% 3.2%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 0.01rem solid #d4dde4;
  }
  .title_left {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .name{
      white-space: nowrap;
    }
    div div:nth-child(1) {
      margin-left: 0.2rem;
    }
    div:nth-child(1) {
      color: #333333;
      font-size: 0.32rem;
      img {
        width: 0.8rem;
        height: 0.8rem;
      }
    }
    div div:nth-child(2) {
      margin-left: 0.2rem;
    }

    div:nth-child(2) {
      margin-top: 0.1rem;
      color: #999999;
      font-size: 0.28rem;
    }
  }
  .card_top_title span:nth-child(1) {
    font-weight: bold;
  }
  .card_top_title span img {
    pointer-events: none;
    width: 0.32rem;
    height: 0.25rem;
  }
  .card_content {
    margin-left: 3.2%;
    margin-top: 0.2rem;
    font-size: 0.28rem;
    color: #999999;
    padding-bottom: 0.4rem;
    div:nth-child(2) {
      margin-top: 0.1rem;
    }
  }
}

[theme-mode='black'] .card_wrapper {
  position: relative;
  width: 7.42rem;
  background-color: #1a1a1a;
  font-size: 0.28rem;
  margin: 0 auto;
  .card_top_title {
    padding: 2% 3.2%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 0.01rem solid #222222;
  }
  .title_left {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 32%;
    div:nth-child(1) {
      color: #d2d2d3;
      font-size: 0.32rem;
      img {
        width: 0.8rem;
        height: 0.8rem;
      }
    }
    div:nth-child(2) {
      margin-top: 0.1rem;
      color: #999999;
      font-size: 0.28rem;
      margin-left: 0.2rem;
    }
  }
  .card_top_title span:nth-child(1) {
    font-weight: bold;
  }
  .card_top_title span img {
    pointer-events: none;
    width: 0.32rem;
    height: 0.25rem;
  }
  .card_content {
    margin-left: 3.2%;
    margin-top: 0.2rem;
    font-size: 0.28rem;
    color: #999999;
    padding-bottom: 0.4rem;
    div:nth-child(2) {
      margin-top: 0.1rem;
    }
  }
}

.active_cp_wrapper {
  padding: 0.2rem 0.1rem;
  background-color: #fff;
  border-top: 0.01rem solid #d4dde4;
  box-shadow: inset 0 0 0 0 #ebebeb;
}
.stock_list_wrapper {
  margin-top: 0.2rem;
  margin-bottom: 0.2rem;
}
.stock_list_content {
  width: 7.42rem;
  margin: 0 auto;
}
[theme-mode='black'] .active_cp_wrapper {
  padding: 0.2rem 0.1rem;
  background-color: #1a1a1a;
  border-top: 0.01rem solid #2e2e2e;
  box-shadow: inset 0 0 0 0 #2e2e2e;
}
.cp_detail_content {
  width: 96%;
  display: flex;
  font-size: 0.28rem;
  align-items: center;
  justify-content: space-between;
  margin: 0 auto;
  color: #666666;
  text-align: center;
  padding: 2%;
  margin-top: 1%;
}
[theme-mode='black'] .cp_detail_content {
  width: 96%;
  font-size: 0.28rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #d2d2d3;
  margin: 0 auto;
  text-align: center;
  padding: 2%;
  margin-top: 1%;
}
</style>
